//
//  HomeViewController.m
//  BMS
//
//  Created by 颜魏 on 2024/12/9.
//

#import "HomeViewController.h"
#import "BatteryViewController.h"
#import "DashboardViewController.h"
#import "CellViewController.h"
#import "SettingViewController.h"
#import "DeviceListViewController.h"
#import "BTManager.h"
#import "PlayManager.h"
#import "DAConfig.h"
#import "NSBundle+DAUtils.h"
#import "ProgressHUD.h"
#import "ArrayViewController.h"
#import "CreatGroupViewController.h"
#import "BlutoothGroupModel.h"
#import "ProtectListViewController.h"
#import "HomeSettingViewController.h"

@interface HomeViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *segView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *segBtns;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *segIvs;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *segLabels;
@property (strong, nonatomic) UIScrollView *sv;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottmSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *optBtns;

@property (nonatomic, strong) BatteryViewController *vc1;
@property (nonatomic, strong) ArrayViewController *avc;
@property (nonatomic, assign) BOOL isReadBattery;   //是否在读电量
@property (nonatomic, assign) BOOL isActiveConnect;   //是否是主动连接

@property (nonatomic, assign) NSInteger queryOrder;     //查询指令

@property (nonatomic, assign) NSInteger voltageSingleExceed;            //单节过压
@property (nonatomic, assign) NSInteger voltageSingleLower;             //单节欠压
@property (nonatomic, assign) NSInteger voltageTotalLower;              //总压欠压
@property (nonatomic, assign) NSInteger chargingExceed;                 //充电过流
@property (nonatomic, assign) NSInteger disChargingExceed;              //放电过流
@property (nonatomic, assign) NSInteger disChargingTemperatureExceed;   //放电过温
@property (nonatomic, assign) NSInteger chargingTemperatureLower;       //充电低温
@property (nonatomic, assign) NSInteger disChargingTemperatureLower;    //放电低温
@property (nonatomic, assign) NSInteger voltageDifferenceExceed;        //压差过大

@property (nonatomic, assign) NSInteger preMOS;     //预充MOS管
@property (nonatomic, assign) NSInteger chgMOS;     //充电MOS管
@property (nonatomic, assign) NSInteger dsgMOS;     //放电MOS管
@property (nonatomic, assign) NSInteger preRelay;   //预充继电器
@property (nonatomic, assign) NSInteger chgRelay;   //分口充电继电器
@property (nonatomic, assign) NSInteger dsgRelay;   //分口放电继电器
@property (nonatomic, assign) NSInteger mainRelay;  //同口主继电器

@property (nonatomic, assign) BOOL isEnd;
@property (nonatomic, assign) BOOL isUpgrading;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) CBPeripheral *connectPeripheral;
@property (nonatomic, strong) NSMutableDictionary *diviceNameDict;

@end

@implementation HomeViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.bottmSpace.constant = [UIApplication sharedApplication].statusBarFrame.size.height>20 ? 34 : 0;
    self.topSpace.constant = [UIApplication sharedApplication].statusBarFrame.size.height>20 ? 44 : 20;
    self.isEnd = NO;
    self.isUpgrading = NO;
    self.diviceNameDict = [[NSMutableDictionary alloc] init];

    [self createSubViews];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didConnect:) name:kBTConnectionSucceed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConnect) name:kBTDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disConnect) name:kBTFailToConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(txrxUpdate:) name:kTXRXUpdate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upgradeUpdate:) name:kBTUpgrading object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevicesName:) name:kBTSearchDevicesName object:nil];

    if (self.segIndex < self.segBtns.count && self.segIndex) {
        [self actionSeg:self.segBtns[self.segIndex]];
    }else {
        [self checkItem:0];
    }
    [self beginQuery];
    
    [self checkLanguage];
}

- (void)checkLanguage {
    if (![[DAConfig userLanguage] containsString:@"en"]) {
        [DAConfig setUserLanguage:@"en"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            HomeViewController *homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
            UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:homeVC];
            UIWindow *window = [UIApplication sharedApplication].delegate.window;
            window.rootViewController = nv;
            [window makeKeyAndVisible];
        });
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.isEnd = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.isEnd = YES;
}

- (void)beginQuery {
    [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (self.isEnd) return;
        if (self.isUpgrading) return;
        if (![BTManager sharedBTManager].peripheral) return;
//        if (![BTManager sharedBTManager].peripheral || self.isReadBattery || self.isActiveConnect) {
//            return;
//        }
        switch (self.queryOrder) {
            case 0:
                [self queryBMS];
                break;
            case 1:
                [self queryBatteryTemperature];
                break;
            case 2:
                [self queryBatteryOther];
                break;
            case 3:
                [self queryClock];
                break;
            case 4:
                [self queryBaseClock];
                break;
            default:
                break;
        }
        self.queryOrder ++;
        if (self.queryOrder>4) {
            self.queryOrder = 0;
        }
    }];
}

- (void)createSubViews {
    NSInteger top = [UIApplication sharedApplication].statusBarFrame.size.height+44;
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    CGFloat height = kHeight-top-54-(statusBarHeight>20 ? 34 : 0);
    self.sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, top, kWidth, height)];
    self.sv.bounces = NO;
    self.sv.pagingEnabled = YES;
    self.sv.showsHorizontalScrollIndicator = NO;
    self.sv.delegate = self;
    self.sv.contentSize = CGSizeMake(kWidth*5, height);
    [self.view insertSubview:self.sv belowSubview:self.segView];
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth*4, height)];
    contentView.backgroundColor = [UIColor clearColor];
    [self.sv addSubview:contentView];
    
    self.vc1 = [[BatteryViewController alloc] initWithNibName:@"BatteryViewController" bundle:nil];
    [self addChildViewController:self.vc1];
    [contentView addSubview:self.vc1.view];
    self.vc1.view.frame = CGRectMake(0, 0, kWidth, height);
    
    DashboardViewController *vc2 = [[DashboardViewController alloc] initWithNibName:@"DashboardViewController" bundle:nil];
    [self addChildViewController:vc2];
    [contentView addSubview:vc2.view];
    vc2.view.frame = CGRectMake(kWidth, 0, kWidth, height);

//    self.avc = [[ArrayViewController alloc] initWithNibName:@"ArrayViewController" bundle:nil];
//    self.avc.nv = self.navigationController;
//    [self addChildViewController:self.avc];
//    [contentView addSubview:self.avc.view];
//    self.avc.view.frame = CGRectMake(kWidth*2, 0, kWidth, height);
//    WeakSelf
//    self.avc.clickConnectBlueBlock = ^(BlutoothModel * _Nonnull blue) {
//        weakSelf.isActiveConnect = YES;
//        [BTManager sharedBTManager].isGettingBattery = NO;
//        [[BTManager sharedBTManager] disconnectRootPeripheral];
//        for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
//            if ([p.name isEqualToString:blue.name]) {
//                [weakSelf.sv setContentOffset:CGPointMake(0, 0)];
//                [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Connecting", nil) timer:5];
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [[BTManager sharedBTManager] connectPeripheral:p];
//                });
//                break;
//            }
//        }
//    };
    
    CellViewController *vc3 = [[CellViewController alloc] initWithNibName:@"CellViewController" bundle:nil];
    [self addChildViewController:vc3];
    [contentView addSubview:vc3.view];
    vc3.view.frame = CGRectMake(kWidth*2, 0, kWidth, height);
    
    SettingViewController *vc4 = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
    [self addChildViewController:vc4];
    [self.sv addSubview:vc4.view];
    self.sv.clipsToBounds = NO;
    vc4.view.frame = CGRectMake(kWidth*3, 0, kWidth, height);
}

#pragma mark - action
- (IBAction)actionLeftItem:(id)sender {
}

- (IBAction)actionSet:(id)sender {
    if ([BTManager sharedBTManager].isConnected) {
        HomeSettingViewController *vc = [[HomeSettingViewController alloc] initWithNibName:@"HomeSettingViewController" bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)actionBlueTooth:(id)sender {
//    if (self.selectIndex == 2) {
//        [BTManager sharedBTManager].isGettingBattery = NO;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            DeviceListViewController *vc = [[DeviceListViewController alloc] initWithNibName:@"DeviceListViewController" bundle:nil];
//            [self.navigationController pushViewController:vc animated:YES];
//        });
//    }else {
        [[BTManager sharedBTManager] disconnectRootPeripheral];
        DeviceListViewController *vc = [[DeviceListViewController alloc] initWithNibName:@"DeviceListViewController" bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
//    }
}

- (IBAction)actionProtect:(id)sender {
    ProtectListViewController *vc = [[ProtectListViewController alloc] initWithNibName:@"ProtectListViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)actionSeg:(UIButton *)sender {
    NSInteger index = [self.segBtns indexOfObject:sender];
    [self.sv setContentOffset:CGPointMake(kWidth*index, 0) animated:YES];
    [self checkItem:index];
}

- (void)checkItem:(NSInteger)index {
    for (NSInteger i=0; i<self.segBtns.count; i++) {
        UIButton *btn = self.segBtns[i];
        UIImageView *iv = self.segIvs[i];
        iv.image = [UIImage imageNamed:[NSString stringWithFormat:@"home_seg_%ld%@", i + 1, index == i ? @"_s" : @""]];
        UILabel *label = self.segLabels[i];
        label.textColor = index == i ? SUBJECT_COLOR : [UIColor whiteColor];
    }
}

#pragma mark - sendData
- (void)queryBMS {
    //主机读取电池电压数据
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x26;
    bytes[6] = 0xfc;
    bytes[7] = 0xd0;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryClock {
    //主机读取时钟及保护记录
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD1;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x15;
    bytes[6] = 0xbd;
    bytes[7] = 0x39;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBatteryTemperature {
    //3.2 主控读取电池温度电流等信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x26;
    bytes[4] = 0x00;
    bytes[5] = 0x19;
    bytes[6] = 0x5d;
    bytes[7] = 0x0b;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBatteryOther {
    //主机读取电池其他信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD1;
    bytes[3] = 0x15;
    bytes[4] = 0x00;
    bytes[5] = 0x0c;
    bytes[6] = 0x6d;
    bytes[7] = 0x37;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBaseClock {
    //系统基础参数读取
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0x23;
    bytes[3] = 0x1C;
    bytes[4] = 0x00;
    bytes[5] = 0x04;
    bytes[6] = 0x8E;
    bytes[7] = 0x4B;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.selectIndex = (NSInteger)scrollView.contentOffset.x/kWidth;
    [self checkItem:self.selectIndex];
//    self.avc.showCurrentPage = self.selectIndex == 2;
//    [BTManager sharedBTManager].isGettingBattery = NO;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (self.selectIndex == 2) {
//            for (UIButton *btn in self.optBtns) {
//                btn.hidden = YES;
//            }
//            if (!self.isReadBattery) {
//                self.connectPeripheral = [BTManager sharedBTManager].peripheral;
//                self.isReadBattery = YES;
//                [BTManager sharedBTManager].isGettingBattery = YES;
//            }
//            [self.avc reloadUI];
//        }else {
//            for (UIButton *btn in self.optBtns) {
//                btn.hidden = NO;
//            }
////            if (self.connectPeripheral) {
//                [BTManager sharedBTManager].isGettingBattery = NO;
//                if (!self.isActiveConnect && self.connectPeripheral) {
//                    [[BTManager sharedBTManager] connectPeripheral:self.connectPeripheral];
//                }
//                self.connectPeripheral = nil;
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    self.isReadBattery = NO;
//                });
////            }
//        }
//    });
}

#pragma mark - notification
- (void)upgradeUpdate:(NSNotification *)nf {
    self.isUpgrading = [nf.object integerValue] == 1;
}

- (void)txrxUpdate:(NSNotification *)nf {
//    self.blutoothNameLabel.text = nf.object;
}

- (void)searchDevicesName:(NSNotification *)nf {
    NSMutableDictionary *dict = nf.object;
    [self.diviceNameDict addEntriesFromDictionary:dict];
    if ([BTManager sharedBTManager].peripheral) {
        NSString *name = [self.diviceNameDict objectForKey:[BTManager sharedBTManager].peripheral.name];
        name = name.length>0 ? name : [BTManager sharedBTManager].peripheral.name;
        self.vc1.nameLabel.text = name;
    }
}

- (void)didConnect:(NSNotification *)nf {
    self.isActiveConnect = NO;
    [ProgressHUD hideHUD];
    NSString *name = [self.diviceNameDict objectForKey:[BTManager sharedBTManager].peripheral.name];
    name = name.length>0 ? name : [BTManager sharedBTManager].peripheral.name;
    self.vc1.nameLabel.text = name;
    self.vc1.connectLabek.textColor = SUBJECT_COLOR;
    self.vc1.connectLabek.text = @"Connected";
    self.vc1.editBtn.hidden = NO;
}

- (void)disConnect {
    if (self.isReadBattery || self.isActiveConnect) {
        return;
    }
    self.vc1.nameLabel.text = @"";
    self.vc1.connectLabek.textColor = [UIColor redColor];
    self.vc1.connectLabek.text = @"Disconnected";
    self.vc1.editBtn.hidden = YES;
    [ProgressHUD hideHUD];
}

- (void)didReciveData:(NSNotification *)notification {
    if (self.isUpgrading) return;

    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
    NSLog(@"receieve %@",reciveData);
    if (dataBytes[2]==0x2a) {
        //3.3 主控读取时钟及保护记录等信息
        //AFE1异常标志
        NSInteger afe1 = dataBytes[3+0x09*2];
        //AFE2异常标志
        NSInteger afe2 = dataBytes[3+0x09*2+1];
        //EEP通讯异常标志
        NSInteger eepCommunicate = dataBytes[3+0x0a*2+1];
        //EEP存储异常标志
        NSInteger eepStorage = dataBytes[3+0x0f*2];
        //CBC_CHG异常标志
        NSInteger cbcCHG = dataBytes[3+0x0e*2+1];
        //CBC_DSG异常标志
        NSInteger cbcDSG = dataBytes[3+0x13*2];
        if ((self.preMOS>0) | (self.chgMOS>0) | (self.dsgMOS>0) | (self.preRelay>0)| (self.chgRelay>0) | (self.dsgRelay>0) | (self.mainRelay>0)) {
            cbcDSG = 0;
            cbcDSG = 0;
        }
        NSInteger hardwareAlarm = afe1 + afe2 + eepCommunicate + eepStorage + cbcDSG + cbcCHG;
        NSInteger batteryAlarm = self.voltageSingleExceed + self.voltageSingleLower + self.voltageTotalLower + self.chargingExceed + self.disChargingExceed + self.disChargingTemperatureExceed + self.disChargingTemperatureLower + self.voltageDifferenceExceed;
        if(hardwareAlarm + batteryAlarm > 0) {
            [[PlayManager sharedManager] playAudio];
        }else {
            [[PlayManager sharedManager] stopAudio];
        }
    }
    if (dataBytes[2]==0x18) {
        //主机读取电池其他信息 3.4
        NSInteger secondByte = dataBytes[4];
        //预充MOS管
        self.preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
        //充电MOS管
        self.chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
        //放电MOS管
        self.dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
        //预充继电器
        self.preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
        //分口充电继电器
        self.chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
        //分口放电继电器
        self.dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
        //同口主继电器
        self.mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
    }
    if ( (dataBytes[2]==0x32)& (reciveData.length>30)) {
        //3.2 主控读取电池温度电流等信息
        //三级保护信息
        NSInteger thirdSafeystatus = dataBytes[3+0x16*2];
        NSInteger thirdSafeystatusSecondbyte = dataBytes[3+0x16*2+1];
        //单节过压
        self.voltageSingleExceed = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;
        //单节欠压
        self.voltageSingleLower = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;
        //总压欠压
        self.voltageTotalLower = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;
        //充电过流
        self.chargingExceed = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;
        //放电过流
        self.disChargingExceed = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;
        //放电过温
        self.disChargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;
        //充电低温
        self.chargingTemperatureLower = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;
        //放电低温
        self.disChargingTemperatureLower = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;
        //压差过大
        self.voltageDifferenceExceed = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;
    }
}


@end
